<template>
  <v-card class="border" rounded="lg" variant="flat">
    <v-tabs v-model="tab" color="primary">
      <v-tab value="general">
        <v-icon start>mdi-cog</v-icon>
        General
      </v-tab>
      <v-tab value="account">
        <v-icon start>mdi-account</v-icon>
        Account
      </v-tab>
      <v-tab value="notifications">
        <v-icon start>mdi-bell</v-icon>
        Notifications
      </v-tab>
      <v-tab value="security">
        <v-icon start>mdi-shield-lock</v-icon>
        Security
      </v-tab>
    </v-tabs>

    <v-card-text>
      <v-window v-model="tab">
        <v-window-item value="general">
          <v-card class="border" rounded="lg" variant="flat">
            <v-card-title>General Settings</v-card-title>
            <v-card-text>
              <v-form @submit.prevent="saveSettings">
                <v-row>
                  <v-col cols="12" md="6">
                    <v-text-field
                      v-model="settings.siteName"
                      label="Site Name"
                      required
                      variant="outlined"
                    />
                  </v-col>
                  <v-col cols="12" md="6">
                    <v-text-field
                      v-model="settings.siteUrl"
                      label="Site URL"
                      required
                      variant="outlined"
                    />
                  </v-col>
                  <v-col cols="12">
                    <v-textarea
                      v-model="settings.siteDescription"
                      label="Site Description"
                      rows="3"
                      variant="outlined"
                    />
                  </v-col>
                  <v-col cols="12" md="6">
                    <v-select
                      v-model="form.timezone"
                      item-title="name"
                      item-value="value"
                      :items="timezones"
                      label="Timezone"
                      variant="outlined"
                    />
                  </v-col>
                  <v-col cols="12" md="6">
                    <v-select
                      v-model="settings.dateFormat"
                      :items="dateFormats"
                      label="Date Format"
                      variant="outlined"
                    />
                  </v-col>
                  <v-col cols="12">
                    <v-btn color="primary" type="submit" variant="flat">
                      Save Changes
                    </v-btn>
                  </v-col>
                </v-row>
              </v-form>
            </v-card-text>
          </v-card>
        </v-window-item>

        <v-window-item value="account">
          <v-card class="border" rounded="lg" variant="flat">
            <v-card-title>Account Settings</v-card-title>
            <v-card-text>
              <v-form @submit.prevent="updateProfile">
                <v-row>
                  <v-col class="d-flex flex-column align-center" cols="12">
                    <v-avatar class="mb-4" size="120">
                      <v-img
                        :alt="'Profile picture of ' + form.firstName"
                        :src="form.avatar || 'https://cdn.vuetifyjs.com/images/profiles/michael.jpg'"
                      />
                    </v-avatar>
                    <v-btn
                      class="mt-4"
                      color="primary"
                      size="small"
                      type="button"
                      @click="changeAvatar"
                    >
                      <v-icon>mdi-camera</v-icon>
                    </v-btn>
                    <input
                      ref="avatarInput"
                      accept="image/*"
                      style="display: none"
                      type="file"
                      @change="handleFileUpload"
                    >
                  </v-col>
                  <v-col cols="12" md="6">
                    <v-text-field
                      v-model="form.firstName"
                      label="First Name"
                      required
                      :rules="[v => !!v || 'First name is required']"
                      variant="outlined"
                    />
                  </v-col>
                  <v-col cols="12" md="6">
                    <v-text-field
                      v-model="currentPassword"
                      class="mb-4"
                      label="Current Password"
                      prepend-icon="mdi-lock"
                      type="password"
                      variant="outlined"
                    />
                  </v-col>
                  <v-col cols="12">
                    <v-textarea
                      v-model="form.bio"
                      label="Bio"
                      rows="3"
                      :rules="[v => v.length <= 200 || 'Bio must be less than 200 characters']"
                      variant="outlined"
                    />
                  </v-col>
                  <v-col cols="12">
                    <v-btn color="primary" type="submit" variant="flat">
                      Update Profile
                    </v-btn>
                  </v-col>
                </v-row>
              </v-form>
            </v-card-text>
          </v-card>
        </v-window-item>

        <v-window-item value="notifications">
          <v-card class="border" rounded="lg" variant="flat">
            <v-card-title>Notification Preferences</v-card-title>
            <v-card-text>
              <v-list>
                <v-list-item v-for="(item, i) in notifications" :key="i">
                  <template #prepend>
                    <v-checkbox v-model="item.enabled" hide-details />
                  </template>
                  <v-list-item-title>{{ item.title }}</v-list-item-title>
                  <v-list-item-subtitle>{{ item.description }}</v-list-item-subtitle>
                </v-list-item>
              </v-list>
              <v-btn class="mt-4" color="primary" variant="flat" @click="saveNotifications">
                Save Preferences
              </v-btn>
            </v-card-text>
          </v-card>
        </v-window-item>

        <v-window-item value="security">
          <v-card class="border" rounded="lg" variant="flat">
            <v-card-title>Security Settings</v-card-title>
            <v-card-text>
              <v-alert class="mb-4" type="info">
                Keep your account secure with these security settings.
              </v-alert>

              <v-list>
                <v-list-item>
                  <template #prepend>
                    <v-avatar class="me-4" color="primary" size="40">
                      <v-icon>mdi-shield-check</v-icon>
                    </v-avatar>
                  </template>
                  <v-list-item-title>Two-Factor Authentication</v-list-item-title>
                  <v-list-item-subtitle>
                    Add an extra layer of security to your account
                  </v-list-item-subtitle>
                  <template #append>
                    <v-checkbox
                      v-model="form.notifications.email"
                      hide-details
                      label="Email notifications"
                    />
                  </template>
                </v-list-item>

                <v-divider class="my-2" />

                <v-list-item>
                  <template #prepend>
                    <v-avatar class="me-4" color="warning" size="40">
                      <v-icon>mdi-key</v-icon>
                    </v-avatar>
                  </template>
                  <v-list-item-title>Change Password</v-list-item-title>
                  <v-list-item-subtitle>
                    Update your account password
                  </v-list-item-subtitle>
                  <template #append>
                    <v-btn color="primary" variant="flat" @click="changePassword">
                      Change
                    </v-btn>
                  </template>
                </v-list-item>

                <v-divider class="my-2" />

                <v-list-item>
                  <template #prepend>
                    <v-avatar class="me-4" color="error" size="40">
                      <v-icon>mdi-logout</v-icon>
                    </v-avatar>
                  </template>
                  <v-list-item-title>Logout from all devices</v-list-item-title>
                  <v-list-item-subtitle>
                    Sign out from all devices except this one
                  </v-list-item-subtitle>
                  <template #append>
                    <v-btn color="error" variant="flat" @click="logoutAll">
                      Logout All
                    </v-btn>
                  </template>
                </v-list-item>
              </v-list>
            </v-card-text>
          </v-card>
        </v-window-item>
      </v-window>
    </v-card-text>
  </v-card>
</template>

<script setup lang="ts">
  import { ref } from 'vue'

  const user = ref<UserProfile>({
    firstName: '',
    lastName: '',
    email: '',
    avatar: '',
    bio: '',
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    notifications: {
      email: true,
      push: true,
      sms: false,
    },
  })

  interface UserProfile {
    firstName: string
    lastName: string
    email: string
    avatar: string
    bio: string
    timezone: string
    notifications: {
      email: boolean
      push: boolean
      sms: boolean
    }
  }

  interface Settings {
    siteName: string
    siteUrl: string
    siteDescription: string
    timezone: string
    dateFormat: string
  }

  // Refs
  const tab = ref('general')
  const avatarInput = ref<HTMLInputElement | null>(null)
  const currentPassword = ref('')
  // 通知设置
  const notifications = ref([
    {
      title: 'Email Notifications',
      description: 'Receive email notifications',
      enabled: true,
      type: 'email',
    },
    {
      title: 'Push Notifications',
      description: 'Receive push notifications',
      enabled: true,
      type: 'push',
    },
    {
      title: 'SMS Notifications',
      description: 'Receive SMS notifications',
      enabled: false,
      type: 'sms',
    },
  ])

  // Settings
  const settings = ref<Settings>({
    siteName: 'Admin Dashboard',
    siteUrl: 'https://example.com',
    siteDescription: 'A modern admin dashboard built with Vuetify',
    timezone: 'UTC',
    dateFormat: 'MM/DD/YYYY',
  })

  // User profile
  const form = ref<UserProfile>({
    firstName: 'John',
    lastName: 'Doe',
    email: 'john.doe@example.com',
    bio: 'A passionate developer',
    avatar: 'https://cdn.vuetifyjs.com/images/profiles/michael.jpg',
    timezone: 'UTC',
    notifications: {
      email: true,
      push: false,
      sms: false,
    },
  })

  // Select options
  const timezones = [
    { name: 'UTC', value: 'UTC' },
    { name: 'GMT', value: 'GMT' },
    { name: 'EST', value: 'EST' },
    { name: 'PST', value: 'PST' },
    'UTC-12:00',
    'UTC-11:00',
    'UTC-10:00',
    'UTC-09:00',
    'UTC-08:00',
    'UTC-07:00',
    'UTC-06:00',
    'UTC-05:00',
    'UTC-04:00',
    'UTC-03:00',
    'UTC-02:00',
    'UTC-01:00',
    'UTC',
    'UTC+01:00',
    'UTC+02:00',
    'UTC+03:00',
    'UTC+04:00',
    'UTC+05:00',
    'UTC+06:00',
    'UTC+07:00',
    'UTC+08:00',
    'UTC+09:00',
    'UTC+10:00',
    'UTC+11:00',
    'UTC+12:00',
    'UTC+13:00',
    'UTC+14:00',
  ]

  const dateFormats = [
    'MM/DD/YYYY',
    'DD/MM/YYYY',
    'YYYY-MM-DD',
    'MMMM D, YYYY',
    'D MMMM, YYYY',
  ]

  function saveSettings () {
    // Save settings logic
    console.log('Saving settings:', settings.value)
    // Show success message
    alert('Settings saved successfully!')
  }

  function updateProfile () {
    // Update profile logic
    console.log('Updating profile:', user.value)
    // Show success message
    alert('Profile updated successfully!')
  }

  function saveNotifications () {
    // 保存通知首选项
    const updatedNotifications: { [key: string]: boolean } = {}
    for (const item of notifications.value) {
      updatedNotifications[item.type] = item.enabled
    }
    user.value.notifications = {
      email: updatedNotifications.email || false,
      push: updatedNotifications.push || false,
      sms: updatedNotifications.sms || false,
    }

    console.log('Saving notifications:', user.value.notifications)
    // 显示成功消息
    alert('通知首选项已保存！')
  }

  const changeAvatar = (): void => {
    if (avatarInput.value) {
      avatarInput.value.click()
    }
  }

  const handleFileUpload = (event: Event): void => {
    const target = event.target as HTMLInputElement
    if (target.files && target.files[0]) {
      const reader = new FileReader()
      reader.addEventListener('load', e => {
        if (e.target?.result && form.value) {
          form.value.avatar = e.target.result as string
        }
      })
      reader.readAsDataURL(target.files[0])
    }
  }

  function changePassword () {
    // Open change password dialog
    console.log('Opening change password dialog')
    // In a real app, you would open a dialog here
    alert('Open change password dialog')
  }

  function logoutAll () {
    // Logout from all devices
    console.log('Logging out from all devices')
    // In a real app, you would call an API to logout from all devices
    alert('Logged out from all devices')
  }
</script>

<style scoped>
.avatar-edit {
  position: absolute;
  right: 0;
  bottom: 0;
  background-color: white !important;
  border: 2px solid white;
}
</style>
